package mysql

import (
	"database/sql"
	"github.com/didi/gendry/scanner"
	"time"

	"github.com/didi/gendry/manager"
	_ "github.com/go-sql-driver/mysql"

	"gitee.com/huerbiao/robot/config"
)

// 用户服务数据库定义
var RobotRead *sql.DB
var RobotWrite *sql.DB

// 初始化连接
func InitConnect() {
	var mysqlCnf config.MysqlCnf
	mysqlCnf.Init()
	//设置dd的db插件可以正常解析json
	scanner.SetTagName("json")
	RobotRead = newCli(mysqlCnf.Conf("robot_read"))
	RobotWrite = newCli(mysqlCnf.Conf("robot_write"))
}

// 创建cli
func newCli(config config.MyConf) *sql.DB {
	cli, err := manager.New(config.Dbname, config.Username, config.Password, config.IP).Set(
		manager.SetCharset(config.Charset),
		manager.SetAllowCleartextPasswords(true),
		manager.SetInterpolateParams(true),
		manager.SetTimeout(1*time.Second),
		manager.SetReadTimeout(1*time.Second),
		//manager.SetLoc("Local"),
	).Port(config.Port).Open(true)
	if err != nil {
		panic(err)
		return nil
	}
	cli.SetMaxIdleConns(config.MaxIdleConns)
	cli.SetMaxOpenConns(config.MaxOpenConns)
	cli.SetConnMaxLifetime(time.Duration(config.ConnMaxLifetime) * time.Second)
	cli.SetConnMaxIdleTime(time.Duration(config.ConnMaxIdleTime) * time.Second)

	err = cli.Ping()
	if err != nil {
		panic(err)
		return nil
	}
	return cli
}
